<?php
namespace app\admin\controller;
use think\Controller;
use think\Validate;
use app\admin\model\Banner as BannerModel;

class Banner extends Controller
{
	private  $bannerModel;
    public function _initialize() {
        $this->bannerModel = new BannerModel();
    }
	public function index()
	{
		$where = [
			'status' => ['neq',-1],
		];
		$count = $this->bannerModel->where($where)->count();
	
		$bannerlist = $this->bannerModel->getBanners();
		return $this->fetch('',[
			'bannerlist' => $bannerlist,
			'count' => $count,
		]);
	}

	// 添加轮播图
	public function add()
	{
		$data = input('post.');
		$file = request()->file('banner');
		$info = $file->validate(['size'=>2000000,'exe'=>'jpg,png,gif'])->rule('uniqid')->move(ROOT_PATH.'public'.DS.'upload');
		if ($info) {
			unset($data['banner']);
			$data['status'] = 1;
			$data['src'] = '/upload/'.$info->getFilename();
			$res = $this->bannerModel->save($data);
			if ($res) {
				$this->success('添加成功');
			} else {
				$this->error('添加失败');
			}
		} else {
			echo $file->getError();
		}
	}

	// 轮播图排序功能
	public function listorder($id,$listorder)
	{
		$res = $this->bannerModel->save(['listorder'=>$listorder],['id'=>$id]);
		if ($res) {
			$this->result($_SERVER['HTTP_REFERER'], 1, 'success');
		} else {
			$this->result($_SERVER['HTTP_REFERER'], 0, '更新失败');
		}
	}

	// 状态
	public function status()
	{
		if (!request()->isGet()) {
			$this->error('请求不合法');
		}
		$data = input('get.');
		$res = $this->bannerModel->save(['status'=>$data['status']],['id'=>$data['id']]);
		if ($res) {
			$this->success('状态更改成功');
		} else {
			$this->error('状态更改失败');
		}
	}

	// 轮播图编辑
	public function edit()
	{
		$id = input('get.id');
		$banner = $this->bannerModel->get($id);
		return $this->fetch('',[
			'banner' => $banner,
		]);
	}

	// 保存修改
	public function save()
	{
		if (!request()->isPost()) {
			$this->error('请求不合法');
		}
		$data = input('post.');
		$file = request()->file('img');
		if ($file) {
			$info = $file->validate(['size'=>2000000,'exe'=>'jpg,png,gif'])->rule('uniqid')->move(ROOT_PATH.'public'.DS.'upload');
			$newPic = '/upload/'.$info->getFilename();
			$res = $this->bannerModel->save([
				'src' => $newPic,
				'url' => $data['url'],
			],['id'=>$data['id']]);
			if ($res) {
				$this->success('更新成功');
			} else {
				$this->error('更新失败');
			}
		} else {
			if ($data['old_url'] == $data['url']) {
				 $this->error('没有进行任何修改');
			} else {
				$res = $this->bannerModel->save([
					'url' => $data['url'],
				],['id'=>$data['id']]);
				if ($res) {
					$this->success('更新成功');
				} else {
					$this->error('更新失败');
				}
			}
		}
	}
}